# (1)取不同的节点数量 ，判断连通率与通信半径的关系
import numpy as np
import matplotlib.pyplot as plt
import randomGraph
import generateMatrix
import time


def demo01(node_number, total_count):
    """
    :param node_number: 节点数量
    :param total_count: 迭代总次数
    :return:
    """
    # 存放通信半径
    radius = np.zeros((len(node_number), 100))

    # 每次的连通性结果
    per_res = np.zeros((len(node_number), 100))

    for nodeNumber in node_number:
        for per_radius in range(1, 101):
            # 横轴标  通信半径
            radius[node_number.index(nodeNumber)][per_radius - 1] = per_radius / 100

            # 计数
            count = 0
            # 迭代total_count次
            for i in range(0, total_count):
                # 每次迭代中网络都要重新随机生成
                # 根据结点数量随机生成单位面积中的网络
                graph = randomGraph.generate_graph_by_node(nodeNumber)
                # 根据随机网络节点生成初始化的邻接矩阵
                init_array = generateMatrix.get_matrix_by_graph_and_radius(graph, per_radius / 100)
                # 如果网络全连通则count++
                _, is_bool = generateMatrix.check_n_is_link(init_array, nodeNumber)
                if is_bool:
                    count += 1
                print("step 1 => ", "nodeNumber=", nodeNumber, ",per_radius=", per_radius / 100, ",i=", i, "/",
                      total_count)
            per_res[node_number.index(nodeNumber)][per_radius - 1] = count / total_count
        print("节点数为", nodeNumber, "计算完成")
    # 返回纵坐标的值连通率 返回横轴标通信半径的值
    return per_res, radius


# 绘制结果图
def show_result_01(node_number, result_link_radius, result_link_rate):
    # 曲线标记
    markers = ['+', 'o', 'x', '.', '*']
    colors = ['b', 'g', 'r', 'c', 'm']
    i = 0
    lines = []
    for num in node_number:
        lines.append('n = ' + str(num))
    for data_list in result_link_rate:
        plt.plot(result_link_radius, data_list, color=colors[i], marker=markers[i])
        i += 1
    # 曲线n=x
    plt.legend(lines, loc='lower right')
    plt.xlabel('Communication radius')
    plt.ylabel('Connectivity')
    plt.title('Relationship between connectivity and number of nodes')
    plt.show()


# 运行程序
def operate():
    time_start = time.time()  # 记录开始时间
    # 指定节点个数
    node_number_list = [1, 10, 20, 50, 100]

    # 迭代次数
    totalCount = 1000
    link_rate, link_radius = demo01(node_number_list, totalCount)

    # 展示结果
    show_result_01(node_number_list, link_radius[0], link_rate)

    # 输出结果
    print(link_rate)
    print(link_radius[0])
    time_end = time.time()  # 记录结束时间
    time_sum = time_end - time_start  # 计算的时间差为程序的执行时间，单位为秒/s
    print("已全部完成,共用时" + str(time_sum) + "s")
    print("##################################################")


if __name__ == '__main__':
    operate()
